var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'batch/settle/temp_list';
var _height = $(parent).height()-315,_width = $(parent).width()-2;

var Utils = {
	doQueryClient : function(){
		commonDia = $.dialog({
			title : '选择批发客户',
			content : 'url:'+config.BASEPATH+'batch/client/to_list_dialog',
			data : {multiselect:false},
			width : 650,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				Utils.temp_save(selected, commonDia);
				return false;
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					Utils.temp_save(selected, commonDia);
				}
			},
			cancel:true
		});
	},
	temp_save:function(rowData,commonDia){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_save',
			data:{"ci_code":rowData.ci_code},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.reloadGridData();
					$("#st_client_code").val(rowData.ci_code);
					$("#client_name").val(rowData.ci_name);
					$("#unreceive").val((rowData.ci_receivable-rowData.ci_received).toFixed(2));
					$("#ci_prepay").val(parseFloat(rowData.ci_prepay).toFixed(2));
					$("#realdebt").val((rowData.ci_receivable-rowData.ci_received-rowData.ci_prepay).toFixed(2));
					commonDia.close();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	doQueryBank : function(){
		commonDia = $.dialog({
			title : '选择银行账户',
			content : 'url:'+config.BASEPATH+'money/bank/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#st_ba_code").val(selected.ba_code);
				$("#ba_name").val(selected.ba_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#st_ba_code").val(selected.ba_code);
					$("#ba_name").val(selected.ba_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
			},
			close:function(){
				var selected = commonDia.content.doSelect();
				if(selected){
					$("#st_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	openDetail:function(number,stl_type){
    	var url = '';
    	var data = {oper: 'readonly'};
    	if(stl_type == '0'){
    		url = config.BASEPATH+"batch/sell/to_view/"+number;
    	}else if(stl_type == '1'){
    		url = config.BASEPATH+"batch/sell/to_view/"+number;
    	}else if(stl_type == '3'){
    		url = config.BASEPATH+"batch/fee/to_view/"+number;
    	}
    	if(url == ''){
    		return;
    	}
    	$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
	changCheck:function(rowid,stl_join){
		var st_entire = $("#st_entire").val();
		if(st_entire == "1"){//整单结算
			if(stl_join == "1"){//参与结算
				var st_receivedmore = $("#st_receivedmore").val();
				var rowData = $("#grid").jqGrid("getRowData", rowid);
	        	if(parseFloat(st_receivedmore)< rowData.stl_real_received){
	        		Public.tips({type: 2, content : '可分配金额不足！'});
	        		$("#grid").jqGrid('setSelection', rowid ,false);//反选
	        		return;
	        	}
			}
		}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updateJoin',
			data:{ids:rowid,stl_join:stl_join},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.calcParentMoney();
					$("#grid").jqGrid('setRowData', rowid, {stl_join:stl_join});
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	changAllCheck: function (rowids, stl_join) {
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updateJoin',
			data:{ids:rowids.join(","),stl_join:stl_join},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.calcParentMoney();
					for (var i = 0; i < rowids.length; i++) {
						$("#grid").jqGrid('setRowData', rowids[i], {stl_join:stl_join});
					}
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	temp_entire:function(){
		var st_entire = $("#st_entire").val();
		if(st_entire != "1"){
			return;
		}
		var discount_money = $("#discount_money").val();//优惠金额
    	var prepay = $("#prepay").val();//使用预收款金额
    	var received = $("#received").val();//实收金额
    	discount_money = discount_money == "" || isNaN(discount_money) ? 0.0 : parseFloat(discount_money);
    	prepay = prepay == "" || isNaN(prepay) ? 0.0 : parseFloat(prepay);
    	received = received == "" || isNaN(received) ? 0.0 : parseFloat(received);
    	
    	if(parseFloat($("#realdebt").val()) > 0 && received < 0){
    		Public.tips({type: 2, content : '请输入正数！'});
			$("#received").val("0.00").select();
    		return;
    	}
    	if(discount_money == 0 && prepay == 0 && received == 0){
    		Public.tips({type: 2, content : '请输入自动分配相关金额！'});
			$("#received").focus();
			return;
    	}
    	if(discount_money > totalPositive){
			Public.tips({type: 2, content : '优惠金额不能大于应收金额！'});
			$("#discount_money").val("0.00").select();
			return;
		}
    	if(prepay > totalPositive){
			Public.tips({type: 2, content : '使用预收款金额不能大于应收金额！'});
			$("#prepay").val("0.00").select();
			return;
		}
    	if(discount_money + prepay > totalPositive){
			Public.tips({type: 2, content : '优惠金额与使用预收款金额之和不能大于应收金额！'});
			$("#prepay").val("0.00").select();
			return;
		}
		if (received < totalNegative) {
    		$("#received").val("0.00").select();
    		Public.tips({type: 2, content : '实收金额过小！'});
    		return;
    	}
		$.dialog.confirm('确定要自动分配吗?',function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'batch/settle/temp_entire',
				data:{discount_money:discount_money,prepay:prepay,received:received},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '自动分配成功！'});
						$("#st_receivedmore").val(PriceLimit.formatMoney(data.data.st_receivedmore));
						THISPAGE.reloadGridData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		},
		function(){
		});
	},
	temp_updateRemark:function(rowid,remark){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updateRemark',
			data:{stl_id:rowid,stl_remark:Public.encodeURI(remark)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updateDiscountMoney:function(rowid,money,realMoney){
    	var params = {stl_id:rowid,stl_discount_money:money};
    	if(realMoney != undefined && realMoney != null){
    		params.stl_real_received = realMoney;
    	}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updateDiscountMoney',
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updatePrepay:function(rowid,money,realMoney){
    	var params = {stl_id:rowid,stl_prepay:money};
    	if(realMoney != undefined && realMoney != null){
    		params.stl_real_received = realMoney;
    	}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updatePrepay',
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
    temp_updateRealMoney:function(rowid,money){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'batch/settle/temp_updateRealMoney',
			data:{stl_id:rowid,stl_real_received:money},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	save:function(){
		if (!$("#form1").valid()) {
			return;
		}
		var rowIds = $('#grid').jqGrid('getGridParam', 'selarrrow');
		if (rowIds.length == 0){
			Public.tips({type: 2, content : '没有选择单据进行支付！'});
			return;
		}
		var sum = 0.0;
    	var st_discount_money = $("#st_discount_money").val();
    	var st_prepay = $("#st_prepay").val();
    	var st_received = $("#st_received").val();
    	sum += parseFloat(st_discount_money)+parseFloat(st_prepay)+parseFloat(st_received);
    	if(sum == 0){
    		Public.tips({type: 2, content : '结算金额为0，无法保存!'});
            return;
    	}
    	var st_receivedmore = $("#st_receivedmore").val();
    	var st_entire = $("#st_entire").val();
    	if(st_entire == "1"){//整单结算
    		sum += parseFloat(st_receivedmore);
    	}
    	var tip = "";
    	tip += $("#client_name").val()+"：<br/>";
    	tip += "应收账款："+$("#unreceive").val()+"元。<br/>";
    	tip += "本次结算："+sum.toFixed(2)+"元，其中优惠金额："+st_discount_money+"元，使用预收款："+st_prepay+"元，实收金额："+st_received+"元。"
    	if(st_entire == "1"){
    		tip += "<br/>转入预收款:"+st_receivedmore+"元。";
    	}
    	tip+="<br/><b>你确定要结算单据吗?</b>";
    	$.dialog.confirm(tip,
            function () {
	    		$("#btn-save").attr("disabled",true);
	    		var saveUrl = config.BASEPATH+"batch/settle/save";
	    		if($("#st_id").val() != undefined){
	    			saveUrl = config.BASEPATH+"batch/settle/update";
	    		}
	    		$.ajax({
	    			type:"POST",
	    			url:saveUrl,
	    			data:$('#form1').serialize(),
	    			cache:false,
	    			dataType:"json",
	    			success:function(data){
	    				if(undefined != data && data.stat == 200){
	    					Public.tips({type: 3, content : '保存成功'});
	    					handle.loadData(data.data);
	    				}else{
	    					Public.tips({type: 1, content : data.message});
	    				}
	    				$("#btn-save").attr("disabled",false);
	    			}
	    		});
            },
            function () {
                return;
            }
        );
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.st_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	formatNumberLink : function(val, opt, row){
		var btnHtml = '<a href="javascript:void(0);" onclick="javascript:handle.openDetail(\''+row.stl_bill_number+'\',' + row.stl_type + ');">'+row.stl_bill_number+'</a>';
		return btnHtml;
	},
	formatType:function(val, opt, row){
		if(val == 0){
			return '销售单';
		}else if(val == 1){
			return '退货单';
		}else if(val == 2){
			return '期初单';
		}else if(val == 3){
			return '费用单';
		}
		return val;
	},
	formatState:function(val, opt, row){
		var sum = parseFloat(row.stl_discount_money) + parseFloat(row.stl_prepay) + parseFloat(row.stl_real_received);
    	if(Math.abs(sum) >= Math.abs(parseFloat(row.stl_unreceivable)) || parseFloat(sum).toFixed(2) == parseFloat(row.stl_unreceivable).toFixed(2)){
        	return '已付清';
        }else{
        	return '未付清';
        }
	},
	formatColor:function(rowid){
    	var rowData = $("#grid").jqGrid("getRowData", rowid);
		if(rowData.state == '已付清'){
        	$("#grid").jqGrid('setRowData', rowid, null,{ color: '#696969' });
        }else if(rowData.state == '未付清'){
        	$("#grid").jqGrid('setRowData', rowid, null,{ color : 'red'});
        }
    },
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="新增">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var totalNegative = 0.0;
var totalPositive = 0.0;

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
		if($("#st_id").val() != undefined && $("#st_entire").val() == "1"){//修改页面整单结算选中
    		$("#table_entire").show();
    		$('#grid').jqGrid('setGridHeight', _height-50);
		}
	},
	initDom:function(){
		$("#st_date").val(config.TODAY);
		this.$_entire = $("#td_entire").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        		$("#st_entire").val("1");
        		$("#table_entire").show();
        		$('#grid').jqGrid('setGridHeight', _height-50);
        	}else{//取消
        		$("#st_entire").val("0");
        		$("#table_entire").hide();
        		$('#grid').jqGrid('setGridHeight', _height);
        	}
		}});
		this.selectRow={};
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var stl_receivable=grid.getCol('stl_receivable',false,'sum');
		var stl_received=grid.getCol('stl_received',false,'sum');
		var stl_discount_money_yet=grid.getCol('stl_discount_money_yet',false,'sum');
		var stl_prepay_yet=grid.getCol('stl_prepay_yet',false,'sum');
		var stl_unreceivable=grid.getCol('stl_unreceivable',false,'sum');
		var stl_discount_money=grid.getCol('stl_discount_money',false,'sum');
		var stl_prepay=grid.getCol('stl_prepay',false,'sum');
		var stl_real_received=grid.getCol('stl_real_received',false,'sum');
    	grid.footerData('set',{stl_bill_number:'合计：',
    		stl_receivable:stl_receivable,
    		stl_received:stl_received,
    		stl_discount_money_yet:stl_discount_money_yet,
    		stl_prepay_yet:stl_prepay_yet,
    		stl_unreceivable:stl_unreceivable,
    		stl_discount_money:stl_discount_money,
    		stl_prepay:stl_prepay,
    		stl_real_received:stl_real_received
    	});
    },
    calcParentMoney:function(){
    	var st_entire = $("#st_entire").val();
    	var st_discount_money = 0.0;
        var st_prepay = 0.0;
        var st_received = 0.0;
        var rowIds = $('#grid').jqGrid('getGridParam', 'selarrrow');
        var rowData = null;
        for (var i = 0; i < rowIds.length; i++) {
            rowData = $("#grid").jqGrid("getRowData", rowIds[i]);
            st_discount_money = st_discount_money + parseFloat(rowData.stl_discount_money);
            st_prepay = st_prepay + parseFloat(rowData.stl_prepay);
            st_received = st_received + parseFloat(rowData.stl_real_received);
        }
        $("#st_discount_money").val(st_discount_money.toFixed(2));
        $("#st_prepay").val(st_prepay.toFixed(2));
        $("#st_received").val(st_received.toFixed(2));
        
        $("#discount_money").val(st_discount_money.toFixed(2));
        $("#prepay").val(st_prepay.toFixed(2));
        if(st_entire == 1){//整单结算
        	var receivedmore = parseFloat($("#received").val()) - st_received;
        	$("#st_receivedmore").val(receivedmore.toFixed(2));
        }else{
        	$("#received").val(st_received.toFixed(2));
        	$("#st_receivedmore").val("0.00");
        }
        var realdebt = parseFloat($("#realdebt").val());//实际欠款
        var st_receivedmore = parseFloat($("#st_receivedmore").val());
        var leftdebt = realdebt - st_discount_money - st_received - st_receivedmore;
        $("#leftdebt").val(leftdebt.toFixed(2));
    },
	initGrid:function(){
		var self=this;
		var colModel = [
	    	{label:'单据编号',name: 'stl_bill_number', index: 'stl_bill_number', width: 140,hidden:true},
	    	{label:'单据编号',name: 'numberlink',index: 'stl_bill_number',width:150,formatter: handle.formatNumberLink},
	    	{label:'单据类型',name: 'stl_type', index: 'stl_type', width: 100,formatter: handle.formatType},
	    	{label:'应收总金额',name: 'stl_receivable', index: 'stl_receivable', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'已收金额',name: 'stl_received', index: 'stl_received', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'已优惠金额',name: 'stl_discount_money_yet', index: 'stl_discount_money_yet', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'已使用预收款',name: 'stl_prepay_yet', index: 'stl_prepay_yet', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'未收金额',name: 'stl_unreceivable', index: 'stl_unreceivable', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney},
	    	{label:'优惠金额',name: 'stl_discount_money', index: 'stl_discount_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'使用预收款',name: 'stl_prepay', index: 'stl_prepay', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'实收金额',name: 'stl_real_received', index: 'stl_real_received', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'状态',name: 'state', index: 'state', width: 100,formatter: handle.formatState},
	    	{label:'备注',name: 'stl_remark', index: 'stl_remark', width: 180,editable:true},
	    	{label:'',name: 'stl_join', index: 'stl_join', width: 100,hidden:true}
	    ];
		var datatype = 'local';
		if($("#st_id").val() != undefined){
			datatype = 'json';
		}
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: datatype,
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:true,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'stl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").jqGrid('getDataIDs');
				totalNegative = 0.0;
            	totalPositive = 0.0;
				for (var i = 0; i < ids.length; i++) {
					var rowData = $("#grid").jqGrid("getRowData", ids[i]);
					if (rowData.stl_join == '1') {
						$("#grid").jqGrid('setSelection', ids[i], false);
					}
					if(rowData.state == '已付清'){
                    	$("#grid").jqGrid('setRowData', ids[i], null,{ color: '#696969' });
                    }else if(rowData.state == '未付清'){
                    	$("#grid").jqGrid('setRowData', ids[i], null,{ color : 'red'});
                    }
					if(parseFloat(rowData.stl_unreceivable)<0){
                    	totalNegative +=parseFloat(rowData.stl_unreceivable);
                    }else{
                    	totalPositive +=parseFloat(rowData.stl_unreceivable);
                    }
				}
				THISPAGE.gridTotal();
				THISPAGE.calcParentMoney();
			},
			loadError: function(xhr, status, error){		
			},
			onSelectAll: function(aRowids, status) {
				handle.changAllCheck(aRowids, status ? "1" : "0");
            },
            onSelectRow: function (rowId, status) {
            	handle.changCheck(rowId, status ? "1" : "0");
            },
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				var st_entire = $("#st_entire").val();
				if(self.selectRow.value == value){
					return self.selectRow.value;
				}
				var selIds = $('#grid').jqGrid('getGridParam', 'selarrrow');
				var selected = false;
				for (var i = 0; i < selIds.length; i++) {
		        	if(rowid == selIds[i]){
		        		selected = true;
		        		break;
		        	}
		        }
				if(!selected){
					Public.tips({type: 2, content : '请选中该行再进行修改！'});
					return self.selectRow.value;//若没选中该行,则该行不允许修改
				}
				if(cellname == 'stl_remark'){
					handle.temp_updateRemark(rowid, value);
					return value;
				}
				if(cellname == 'stl_discount_money' || cellname == 'stl_prepay' || cellname == 'stl_real_received'){
					if(value == '' || isNaN(value)){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return parseFloat(value).toFixed(2);
					}
					if(cellname == 'stl_prepay'){//检查预付款是否超过余额
				        var row = null;
				        var stl_prepay_sum = 0.0;
				        for (var i = 0; i < selIds.length; i++) {
				        	if(rowid == selIds[i]){
				        		stl_prepay_sum += parseFloat(value);
				        	}else{
				        		row = $("#grid").jqGrid("getRowData", selIds[i]);
				        		stl_prepay_sum += parseFloat(row.stl_prepay);
				        	}
				        }
				        if(stl_prepay_sum > parseFloat($("#ci_prepay").val())){
				        	Public.tips({type: 2, content : '预收款余额不足！'});
							return self.selectRow.value;
				        }
					}
					
					var minus = parseFloat(value) - parseFloat(self.selectRow.value);
            		if(st_entire == 1 && cellname == 'stl_real_received'){//自动分配时修改实收金额时验证分配余额是否充足
            			if(minus > 0 && minus > parseFloat($("#st_receivedmore").val())){
                			Public.tips({type: 2, content : '可分配余额不足！'});
                			return self.selectRow.value;
                		}
            		}
					
					var stl_real_received = null;
            		var rowData = $("#grid").jqGrid("getRowData", rowid);
            		if(cellname == 'stl_discount_money' || cellname == 'stl_prepay'){
            			if(rowData.stl_unreceivable < 0){
            				Public.tips({type: 2, content : '未收金额为负数，不可以修改此金额！'});
            				return self.selectRow.value;
            			}
            			if(cellname == 'stl_discount_money' && parseFloat(value) < 0){
            				Public.tips({type: 2, content : '优惠金额不能输入负数！'});
                			return self.selectRow.value;
            			}
            			if(cellname == 'stl_prepay' && parseFloat(value) < 0){
            				Public.tips({type: 2, content : '使用预收款金额不能输入负数！'});
                			return self.selectRow.value;
            			}
            			if(cellname == 'stl_discount_money' && Math.abs(parseFloat(value)) > Math.abs(parseFloat(rowData.stl_unreceivable))){
            				Public.tips({type: 2, content : '优惠金额不能大于应收金额！'});
                			return self.selectRow.value;
            			}
            			if(cellname == 'stl_discount_money' && 
            					Math.abs(parseFloat(value)+parseFloat(rowData.stl_prepay)) > Math.abs(parseFloat(rowData.stl_unreceivable))){
            				Public.tips({type: 2, content : '预收款金额和优惠金额之和不能大于应收金额！'});
                			return self.selectRow.value;
            			}
            			if(cellname == 'stl_prepay' && Math.abs(parseFloat(value)) > Math.abs(parseFloat(rowData.stl_unreceivable))){
            				Public.tips({type: 2, content : '预收款金额不能大于应收金额！'});
                			return self.selectRow.value;
            			}
            			if(cellname == 'stl_prepay' && 
            					Math.abs(parseFloat(value)+parseFloat(rowData.stl_discount_money)) > Math.abs(parseFloat(rowData.stl_unreceivable))){
            				Public.tips({type: 2, content : '预付款金额和优惠金额之和不能大于应收金额！'});
                			return self.selectRow.value;
            			}
            			var sum = 0;
            			if(cellname == 'stl_discount_money'){
            				sum += parseFloat(value) + parseFloat(rowData.stl_prepay) + parseFloat(rowData.stl_real_received);
            			}else if(cellname == 'stl_prepay'){
            				sum += parseFloat(value) + parseFloat(rowData.stl_discount_money) + parseFloat(rowData.stl_real_received);
            			}
            			if(minus > 0){//增加优惠金额或预收款使用,则根据情况减少实收金额增加可分配余额
            				if(Math.abs(sum) > Math.abs(rowData.stl_unreceivable)){
            					var moreMoney = sum - parseFloat(rowData.stl_unreceivable);//实收金额减少或者可分配余额增加的金额
            					stl_real_received = parseFloat(rowData.stl_real_received) - moreMoney;
            					if(cellname == 'stl_discount_money'){
            						handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}else if(cellname == 'stl_prepay'){
            						handle.temp_updatePrepay(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}
            					$("#grid").jqGrid('setRowData', rowid, {stl_real_received:stl_real_received});
            					return parseFloat(value).toFixed(2);
            				}else{
            					if(st_entire == 1){
            						if(cellname == 'stl_discount_money'){
                						handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), null);
                					}else if(cellname == 'stl_prepay'){
                						handle.temp_updatePrepay(rowid, parseFloat(value).toFixed(2), null);
                					}
            						return parseFloat(value).toFixed(2);
            					}else{
            						var moreMoney = sum - parseFloat(rowData.stl_unreceivable);
            						stl_real_received = parseFloat(rowData.stl_real_received) - moreMoney;
            						if(cellname == 'stl_discount_money'){
                						handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), stl_real_received);
                					}else if(cellname == 'stl_prepay'){
                						handle.temp_updatePrepay(rowid, parseFloat(value).toFixed(2), stl_real_received);
                					}
            						$("#grid").jqGrid('setRowData', rowid, {stl_real_received:stl_real_received});
                					return parseFloat(value).toFixed(2);
            					}
            				}
            			}else if(minus < 0){//减少优惠金额或预收款使用,则根据是否选中自动分配和可分配余额进行分配实收金额
            				if(st_entire == 1){//检查可分配余额是否够进行分配
            					var st_receivedmore = parseFloat($("#st_receivedmore").val());
            					if(st_receivedmore <= 0){
            						stl_real_received = null;
            					}else if(sum + st_receivedmore >= parseFloat(rowData.stl_unreceivable)){
            						var moreMoney = sum - parseFloat(rowData.stl_unreceivable);
            						stl_real_received = parseFloat(rowData.stl_real_received) - moreMoney;
            						$("#grid").jqGrid('setRowData', rowid, {stl_real_received:stl_real_received});
            					}else{
            						var moreMoney = -st_receivedmore;
            						stl_real_received = parseFloat(rowData.stl_real_received) - moreMoney;
            						$("#grid").jqGrid('setRowData', rowid, {stl_real_received:stl_real_received});
            					}
            					if(cellname == 'stl_discount_money'){
            						handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}else if(cellname == 'stl_prepay'){
            						handle.temp_updatePrepay(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}
            					return parseFloat(value).toFixed(2);
            				}else{
            					var moreMoney = sum - parseFloat(rowData.stl_unreceivable);
            					stl_real_received = parseFloat(rowData.stl_real_received) - moreMoney;
            					
            					if(cellname == 'stl_discount_money'){
            						handle.temp_updateDiscountMoney(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}else if(cellname == 'stl_prepay'){
            						handle.temp_updatePrepay(rowid, parseFloat(value).toFixed(2), stl_real_received);
            					}
        						$("#grid").jqGrid('setRowData', rowid, {stl_real_received:stl_real_received});
            					return parseFloat(value).toFixed(2);
            				}
            			}
            		}
            		if(cellname == 'stl_real_received'){
            			var tempSum = 0;
            			tempSum += parseFloat(value);
            			tempSum += parseFloat(rowData.stl_discount_money) + parseFloat(rowData.stl_prepay);
            			if(rowData.stl_unreceivable >= 0 && (tempSum > rowData.stl_unreceivable || tempSum < 0)){
            				Public.tips({type: 2, content : '实收金额超出范围！'});
    						return self.selectRow.value;
            			}else if(rowData.stl_unreceivable < 0 && (tempSum < rowData.stl_unreceivable || tempSum > 0)){
            				Public.tips({type: 2, content : '实收金额超出范围！'});
    						return self.selectRow.value;
            			}
            			handle.temp_updateRealMoney(rowid, parseFloat(value).toFixed(2));
                		return parseFloat(value).toFixed(2);
            		}
				}
				return value;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				if(self.selectRow.value == value){
					return;
				}
				if(cellname == 'stl_discount_money' || cellname == 'stl_prepay' || cellname == 'stl_real_received'){
					var rowData = $("#grid").jqGrid("getRowData", rowid);
					rowData.state = '';
					$("#grid").jqGrid('setRowData', rowid, rowData);
        			handle.formatColor(rowid);
        			THISPAGE.gridTotal();
    				THISPAGE.calcParentMoney();
				}
			}
	    });
	},
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
        $('#AutoMatch').click(function(e){
        	e.preventDefault();
        	handle.temp_entire();
        });
        $('#discount_money').on('keyup',function(e){
    		if (e.keyCode==13){
    			$("#prepay").select();
    		}
    	});
        $('#prepay').on('keyup',function(e){
    		if (e.keyCode==13){
    			$("#received").select();
    		}
    	});
        $('#received').on('keyup',function(e){
    		if (e.keyCode==13){
    			$('#AutoMatch').click();
    		}
    	});
        $('#discount_money').on('blur',function(){
        	if(parseFloat(this.value) == 0){
        		return;
        	}
        	if(parseFloat(this.value) > totalPositive){
    			Public.tips({type: 2, content : '优惠金额不能大于未收金额！'});
    			$('#discount_money').val('0.00').select();
    		}
    		if(parseFloat(this.value)+parseFloat($("#prepay").val()) > totalPositive){
    			Public.tips({type: 2, content : '优惠金额和预收款使用金额不能大于未收金额！'});
    			$('#discount_money').val('0.00').select();
    		}
    	});
        $('#prepay').on('blur',function(){
        	if(parseFloat(this.value) == 0){
        		return;
        	}
        	if(parseFloat(this.value) > parseFloat($("#ci_prepay").val())){
    			Public.tips({type: 2, content : '预收款余额不足！'});
    			$('#prepay').val('0.00').select();
    		}
    		if(parseFloat(this.value)+parseFloat($("#discount_money").val()) > totalPositive){
    			Public.tips({type: 2, content : '优惠金额和预收款使用金额不能大于未收金额！'});
    			$('#prepay').val('0.00').select();
    		}
    	});
	}
};

THISPAGE.init();